<template>
  <v-page
    v-model="refreshing"
    background="#f5f6fa"
    header-background="white"
    footer-background="white"
    :loading="loading"
    :empty="!loading && !cartList.length"
    empty-oss-src="empty-product.png"
    empty-text="购物车为空"
    @refresh="refreshHandle"
  >
    <template #header>
      <v-navbar :back="false" title="购物车" native />
      <view class="page-header">
        <wd-checkbox
          :model-value="isSelectAll"
          @update:model-value="selectAllHandle"
        >
          全选
        </wd-checkbox>
        <view class="plain-button" @click="toggleEditing">
          {{ isEditing ? '完成' : '管理' }}
        </view>
      </view>
    </template>
    <template #default>
      <view class="cart-list">
        <cart-merchant
          v-for="merchant in cartList"
          :key="merchant.merchant_id"
          :merchant="merchant"
          :is-editing="isEditing"
          :edit-selecting-list="editSelectingList"
          @refresh="refreshCartList"
          @select-sku="selectProduct"
          @edit-select="editSelect"
        />
      </view>
    </template>
    <template #footer>
      <view class="page-footer">
        <template v-if="isEditing">
          <view />
          <v-button
            type="plain"
            :custom-style="{ height: '80rpx', width: '210rpx' }"
            @click="removeSelectingProduct"
          >
            删除
          </v-button>
        </template>
        <template v-else>
          <view class="count-pad">
            <view class="main-text">
              <view class="label">
                合计:
              </view>
              <v-price :price="totalPrice" size="40rpx" />
            </view>
          </view>
          <v-button
            type="primary"
            :disable="selectedCartList.length === 0"
            :custom-style="{ height: '80rpx', width: '210rpx' }"
            :disabled="isDisabled"
            @click="navigateToOrderConfirm"
            @disabled="disabledHandle"
          >
            结算
          </v-button>
        </template>
      </view>
    </template>
    <template #popup>
      <cart-select-popup
        v-model:show="isShowSelect"
        :cart-product="selectingProduct"
        @refresh="refreshCartList"
      />
    </template>
  </v-page>
</template>

<script setup lang="ts">
import CartMerchant from './modules/cart-merchant.vue';
import cartSelectPopup from './modules/cart-select-popup.vue';

const loading = ref(true);
const cartList = ref<CartMerchantVO[]>([]);
const refreshCartList = async () => {
  const response = await $api.getCartList({ all: true });
  uni.hideLoading();
  loading.value = false;
  switch (response.__error) {
    case undefined:
      cartList.value = response.data.list;
      break;
  }
};

const refreshing = ref(false);
const refreshHandle = async () => {
  refreshing.value = true;
  await refreshCartList();
  refreshing.value = false;
};
onShow(async () => {
  // loading.value = true;
  await refreshCartList();
  loading.value = false;
});

const allCartList = computed(() => {
  return cartList.value.flatMap((merchant) => merchant.cart_list);
});
const isSelectAll = computed(() => {
  if (!allCartList.value.length) return false;
  if (isEditing.value) {
    const list = editSelectingList.value;
    return allCartList.value.every((product) => list.includes(product.id));
  } else {
    const avaliableList = allCartList.value.filter((product) => {
      if (product.status === 'DISABLED') return false;
      if (!product.sale_status) return false;
      return true;
    });
    if (avaliableList.length === 0) return false;
    return avaliableList.every((product) => product.selected === 'SELECTED');
  }
});
const selectAllHandle = async () => {
  if (!allCartList.value.length) return;
  if (isEditing.value) {
    const list = allCartList.value.map((product) => product.id);
    editSelectingList.value = isSelectAll.value ? [] : list;
  } else {
    const avaliableList = allCartList.value.filter((product) => {
      if (product.status === 'DISABLED') return false;
      if (!product.sale_status) return false;
      return true;
    });
    const response = await $api.postCartEditSelects(
      avaliableList.map((product) => ({
        id: product.id,
        selected: isSelectAll.value ? 'UNCHECK' : 'SELECTED'
      }))
    );
    switch (response.__error) {
      case undefined:
        refreshCartList();
        break;
    }
  }
};

const selectedCartList = computed(() => {
  return allCartList.value.filter((product) => product.selected === 'SELECTED');
});
const totalPrice = computed(() => {
  return selectedCartList.value.reduce(
    (total, product) => total + (product.sell_price ?? 0) * product.quantity,
    0
  );
});
const isDisabled = computed(() => {
  if (!selectedCartList.value.length) return true;
  return selectedCartList.value.some((product) => {
    if (product.quantity > product.inventory) return true;
    if (!product.sale_status) return true;
    if (product.status === 'DISABLED') return true;
    return false;
  });
});

const getCartList = async (data: OrderGenerateReq[]) => {
  uni.showLoading({ mask: true });
  const response = await $api.postOrderSubmitCart(data, {
    ignoreApiCodes: [700003]
  });
  uni.hideLoading();
  switch (response.__error) {
    case undefined:
      if (response.code === 700003) {
        uni.showToast({ title: response.msg, icon: 'none' });
      } else {
        return response.data.list;
      }
  }
};
const navigateToOrderConfirm = async () => {
  const checkedList = await getCartList(
    selectedCartList.value.map((product) => ({
      sku_id: product.sku_id,
      quantity: product.quantity,
      discount_type: 'NONE' as const,
      multilevel_reflux_setting_id: '',
      landing_page_id: '',
      activity_id: ''
    }))
  );
  if (!checkedList) return;
  const pagestore = $store.page();
  pagestore.setParameters({ list: checkedList });
  uni.navigateTo({ url: '/pages/order/order-confirm?type=cart' });
};
const disabledHandle = () => {
  if (!selectedCartList.value.length) {
    uni.showToast({ title: '请选择商品', icon: 'none' });
  } else if (isDisabled.value) {
    uni.showToast({ title: '商品库存不足或已下架', icon: 'none' });
  }
};

const isEditing = ref(false);
const editSelectingList = ref<string[]>([]);
const toggleEditing = () => {
  if (isEditing.value) {
    isEditing.value = false;
    editSelectingList.value = [];
  } else {
    isEditing.value = true;
    editSelectingList.value = [];
  }
};
const editSelect = (val: boolean, list: string[]) => {
  if (!isEditing.value) return;
  if (val) {
    const newList = [...editSelectingList.value, ...list];
    editSelectingList.value = Array.from(new Set(newList));
  } else {
    const newList = editSelectingList.value.filter((id) => !list.includes(id));
    editSelectingList.value = newList;
  }
};
const removeSelectingProduct = async () => {
  if (!isEditing.value) return;
  if (!editSelectingList.value.length) return;
  uni.showLoading({ mask: true });
  const response = await $api.postCartRemove(
    editSelectingList.value.map((id) => ({ cart_id: id }))
  );
  switch (response.__error) {
    case undefined:
      refreshCartList();
      uni.showToast({ title: '删除成功', icon: 'none' });
      editSelectingList.value = [];
      break;
  }
};

const isShowSelect = ref(false);
const selectingProduct = ref<CartVO>();
const selectProduct = (product: CartVO) => {
  selectingProduct.value = product;
  isShowSelect.value = true;
};
</script>

<style lang="scss" scoped>
.page-header {
  display: flex;
  justify-content: space-between;
  padding: 10rpx 48rpx;
  .plain-button {
    padding: 8rpx 16rpx;
  }
}
.cart-list {
  margin-top: 24rpx;
}
.page-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16rpx 24rpx;
  .count-pad {
    display: flex;
    .main-text {
      display: flex;
      align-items: baseline;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      word-break: break-all;
    }
  }
}
</style>
